2. 两数相加

2. 两数相加

Similar Question

leading to the advanced question

Solution Tips

方案一: 模拟

var addTwoNumbers = function(l1, l2) {
    let cur1 = l1;
    let cur2 = l2;
    let rest = 0;
    let head = new ListNode(0);
    let cur = head;

    while (cur1 !== null || cur2 !== null || rest !== 0) {

        const total = (cur1?.val || 0) + (cur2?.val || 0) + rest;
        const val = total % 10;
        rest = Math.floor(total / 10);
        cur.val = val;

        cur1 = cur1?.next || null;
        cur2 = cur2?.next || null;

        if (cur1 || cur2 || rest !== 0) {
            cur.next = new ListNode(0)
            cur = cur.next;
        }
    }

    return head;
};